package com.atguigu.gmall.cart.api;

import com.atguigu.gmall.cart.service.CartService;
import com.atguigu.gmall.model.product.SkuInfo;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * @author 钟涛
 * @version 1.0
 * @description: TODO
 * @date 2021/12/22 11:22
 */
@RequestMapping("/api/inner/cart")
@RestController
public class CartApiController {
    @Autowired
    private CartService cartService;

    @Autowired
    private StringRedisTemplate redisTemplate;
    @GetMapping("/add/{skuId}")
    public SkuInfo addSkuToCart(@PathVariable("skuId")Long skuId,
                                @RequestParam("skuNum")Integer skuNum,
                                @RequestHeader(value = "userId",required = false) String userId,
                                @RequestHeader(value = "userTempId",required = false) String userTempId,
                                HttpServletRequest request) throws JsonProcessingException {

        String cartKey = cartService.determinCartKey(userId,userTempId);
        SkuInfo skuInfo = cartService.addSkuToCart(skuId, skuNum, cartKey);
        if(StringUtils.isEmpty(userId)){
            redisTemplate.expire(cartKey,365, TimeUnit.DAYS);
        }
        return skuInfo;
    }
}
